
package com.ny.dao;

import com.ny.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String TABLE_NAME = "tb_user";

    // 查询所有用户
    public List<User> findAll() {
        String sql = "SELECT id, name, password FROM " + TABLE_NAME;
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }

    // 根据 ID 查询
    public User findById(Integer id) {
        String sql = "SELECT id, name, password FROM " + TABLE_NAME + " WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }

    // 插入用户
    public int insert(User user) {
        String sql = "INSERT INTO " + TABLE_NAME + " (name, password) VALUES (?, ?)";
        return jdbcTemplate.update(sql, user.getName(), user.getPassword());
    }

    // 动态更新（只更新非空字段）
    public int update(User user) {
        StringBuilder sql = new StringBuilder("UPDATE " + TABLE_NAME + " SET ");
        boolean hasUpdate = false;

        if (user.getName() != null && !user.getName().isEmpty()) {
            sql.append("name = ?");
            hasUpdate = true;
        }

        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            if (hasUpdate) {
                sql.append(", ");
            }
            sql.append("password = ?");
            hasUpdate = true;
        }

        if (!hasUpdate) {
            return 0; // 无字段需要更新
        }

        sql.append(" WHERE id = ?");
        return jdbcTemplate.update(sql.toString(), buildUpdateParams(user));
    }

    // 删除用户
    public int deleteById(Integer id) {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    // 构建更新参数数组（顺序必须与 SQL 中 ? 一致）
    private Object[] buildUpdateParams(User user) {
        java.util.List<Object> params = new java.util.ArrayList<>();
        if (user.getName() != null && !user.getName().isEmpty()) {
            params.add(user.getName());
        }
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            params.add(user.getPassword());
        }
        params.add(user.getId()); // WHERE 条件
        return params.toArray();
    }
}